<template>
  <div class="subcontract-registration-manage">
    <div class="model-title-css">
      <div>设计变更台账</div>
    </div>
    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-tree class="Public-Tree-Class" :data="leftList" :props="defaultProps" ref='treeData' node-key="id" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
      </div>
      <div class="right-box" style="padding-right: 15px">
        <div class="operate_wrap flex">
          <div class="flex-center">
            <div>增减总金额：<span style="color: #fa373c;">{{totalMoney|moneyFilter}}万元</span></div>
          </div>
          <div class="flex-center g-flex flex-right">
            <el-date-picker style="margin-right: 10px;width: 350px" v-model="searchDates" type="daterange" format="yyyy-MM-dd" unlink-panels value-format="yyyy-MM-dd" range-separator="至" start-placeholder="填报开始日期" end-placeholder="填报结束日期" @change="onChangeTime">
            </el-date-picker>
            <!-- <el-date-picker size="small" style="width: 240px" v-model="search.dateStart" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable placeholder="请选择开始日期">
            </el-date-picker>
            <el-date-picker size="small" style="width: 240px;margin-left: 15px" v-model="search.dateEnd" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable placeholder="请选择结束日期">
            </el-date-picker> -->
            <el-input class="input" size="small" style="width: 180px;" v-model="search.code" placeholder="请输入设计变更变更编号" clearable></el-input>
            <el-button class="search" size="small" @click="getList(true)">
              <i class="iconfont icon-sousuo"></i>&nbsp;搜索
            </el-button>
            <el-button class="search" size="small" @click="exportExcel">导出
            </el-button>
          </div>
        </div>
        <div class="list_wrap WholeScroll">
          <el-table class="table-three-blue table-nine-blue " :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">

            <el-table-column show-overflow-tooltip prop="xh" align="center" label="序号" width="60">
              <template slot-scope="scope">
                {{ scope.$index + search.pageNo * search.pageSize + 1 }}
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="sectionName" label="标段" width="140">
              <template slot-scope="scope">
                {{scope.row.sectionName}}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="设计变更编号" prop="designChangeNum" width="150">
              <template slot-scope="scope">
                <div>{{scope.row.designChangeCode}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="变更名称" prop="forecastChangeMoney" width="300">
              <template slot-scope="scope">
                <div>{{scope.row.modifyName}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="主要内容" prop="contractType" min-width="280">
              <template slot-scope="scope">
                <div>{{scope.row.content}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="变更等级" prop="contractType" width="160">
              <template slot-scope="scope">
                <div>{{changeLevelArr[scope.row.changeLevel]?changeLevelArr[scope.row.changeLevel]:'-'}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="增减金额(万元)" prop="contractType" width="170">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.designChangeMoney}}</div>
              </template>
            </el-table-column>
            <!--            <el-table-column show-overflow-tooltip label="申请上报时间" prop="completeTime" width="150">-->
            <!--              <template slot-scope="scope">-->
            <!--                <div>{{scope.row.applyDate}}</div>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column show-overflow-tooltip label="变更申报编号" prop="changeReportNum" width="150">-->
            <!--              <template slot-scope="scope">-->
            <!--                <div>{{scope.row.applyCode}}</div>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!-- <el-table-column show-overflow-tooltip label="批复时间" prop="completeTime" width="150">
              <template slot-scope="scope">
                <div>{{scope.row.replyDate}}</div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column show-overflow-tooltip label="批复金额(万元)" prop="completeTime" width="150">
              <template slot-scope="scope">
                <div>{{scope.row.replyMoney}}</div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column show-overflow-tooltip label="批复主要内容" prop="reportTime" width="280">
              <template slot-scope="scope">
                <div>{{scope.row.replyContent}}</div>
              </template>
            </el-table-column> -->
          </el-table>
          <el-pagination style="float: right; margin-top: 30px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
      <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
      <Detail2 :postDetail="postDetailData2" @reloadList="getList(true)"></Detail2>
    </div>
  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  // doCreateObject
} from '@/utils/publicFun'
import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import crudDict from '@/api/system/dict'
import contractFiling from '@/api/buss/contractFiling'
import publicSearchData from '@/mixins/publicSearchData'
export default {
  mixins: [publicSearchData],
  name: `demo`,
  components: {
    Detail: require(`../designChangeApply/designChangeApply-detail`).default,
    Detail2: require(`../changeCostReport/changeCostReport-detail`).default,
  },
  data() {
    return {
      searchDates: [],
      typeOptions: [
        {
          label: '合同分类',
          value: '',
        },
      ],
      leftList: [],
      defaultTreeKey: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      chooseTreeData: {},
      permission: {
        add: ['100', '1001068:add'],
        show: ['100', '1001068:show'],
        edit: ['100', '1001068:edit'],
        del: ['100', '1001068:del'],
      },

      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      hasAdd: false, //是否有新增权限
      loading: false,
      //  当前查看的文件列表
      nowFileList: [],
      showFileDialog: false,
      list: [{}, {}, {}, {}],
      title: '人员',
      changeLevelArr: {
        '1': '一般',
        '2': '较大',
        '3': '重大'
      },
      addSectionId: '',
      // 搜索参数
      search: {
        dateStart: '',
        dateEnd: '',
        //pageIndex: 0,
        pageNo: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        sectionId: '',
        projectId: '',
        contractName: '',
        contractType: '',
      },
      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      postDetailData2: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      // 向详情子组件的传值
      treeEditDialogData: {
        show: false,
        nowTreeData: []
      },
      totalMoney: 0,
    }
  },
  mounted() {
    this.initData()
    this.getContractArr()
  },
  methods: {
    /** 时间选择器 */
    onChangeTime() {
      if (this.searchDates) {
        this.search.dateStart = this.searchDates[0]
        this.search.dateEnd = this.searchDates[1]
      } else {
        this.search.dateStart = ''
        this.search.dateEnd = ''
      }
    },
    exportExcel() {
      this.$httpPost('/buss/modifyFeeApply/exportLedgerExcel', this.search, { responseType: 'blob' }).then(res => {
        var blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=UTF-8' }) //application/vnd.openxmlformats-officedocument.wordprocessingml.document这里表示doc类型
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) //创建下载的链接
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = decodeURI('设计变更台账.xls') //下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放掉blob对象
        // var href = window.URL.createObjectURL(blob); //创建下载的链接
        // window.location.href = href;
        // window.URL.revokeObjectURL(href); //释放掉blob对象

      }).catch(res => {
        console.log('请求出现错误', res)
        this.$messageError(this.$route.name + '请求失败')
      })

    },
    checkFile(row) {
      console.log(row)
      if (row.hasOwnProperty('fileList') && row.fileList.length > 0) {
        let id = row.fileList[0].id
        this.$publicUpload.preView(id)
      } else {
        this.$messageWarning('暂无文件')
      }
    },
    approve(obj) {
      this.postDetailData = {
        show: true,
        type: 'approve',
        typeName: '审核',
        detailId: obj.id,
      }
    },
    edit(obj) {
      this.postDetailData = {
        show: true,
        type: 'edit',
        typeName: '编辑',
        detailId: obj.id,
      }
    },
    detail(obj) {
      this.postDetailData = {
        show: true,
        type: 'check',
        typeName: '查看',
        detailId: obj.designChangeId,
      }
    },
    detail2(obj) {
      if (obj.applyId) {
        this.postDetailData2 = {
          show: true,
          type: 'check',
          typeName: '查看',
          detailId: obj.applyId,
        }
      }
    },
    del(obj) {
      if (obj.id === '') {
        msgUtil.error2('请先选择要删除的记录！')
        return
      }
      msgUtil.confirm('确认删除该条数据?').then(res => {
        let idlist = []
        idlist.push(obj.id)
        let param = {
          ids: idlist
        }
        contractFiling.del(param).then(res => {
          if (res.code === 200) {
            msgUtil.success2('删除成功!')
            this.getList()
          } else {
            msgUtil.error2(res.data.message)
          }
        })
      })
    },
    getContractArr() {
      this.typeOptions = []
      crudDict.getByCode('contractClassA').then(res => {
        if (res.code === 200) {
          this.typeOptions = res.data;
          // for (var i in data) {
          //   this.typeOptions.push({'value':data[i].id,'label':data[i].name});
          // }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })
    },
    initData() {
      projectSectionInfo.getLeftProjectTree().then(res => {
        if (res.code === 200) {
          this.$set(this, 'leftList', res.data)
          if (this.leftList.length > 0) {
            //默认展开的节点
            this.$nextTick(() => {
              if (this.$headerSearch) {
                if (this.changeHeaderProject) {
                  this.$refs['treeData'].setCurrentKey(this.changeHeaderProject);
                  if (this.defaultTreeKey) {
                    this.defaultTreeKey.push(this.changeHeaderProject)
                  }
                  this.handleNodeClick({
                    id: this.changeHeaderProject,
                    type: 'projectId'
                  })
                } else {
                  this.defaultTreeKey.push(this.leftList[0].id)
                  this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                  if (this.defaultTreeKey) {
                    this.defaultTreeKey.push(this.leftList[0].id)
                  }
                  this.handleNodeClick(this.leftList[0])
                }
              } else {
                this.defaultTreeKey.push(this.leftList[0].id)
                this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.leftList[0].id)
                }
                this.handleNodeClick(this.leftList[0])
              }
            })
          } else {
            this.list = []
          }
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })
    },


    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    handleNodeClick(data) {
      this.search.sectionId = '';
      if (data.type == 'projectId') {
        this.search.projectId = data.id;
      }
      if (data.type == 'sectionId' || data.type == 'contract') {
        this.search.sectionId = data.id;
        this.search.projectId = data.projectId
        this.addSectionId = data.id;
      }
      this.getList(true)
    },
    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      if (column.property === 'designChangeNum') {
        this.detail(row)
      }
      if (column.property === 'changeReportNum') {
        this.detail2(row)
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageNo = 0
      }
      this.list = []
      this.$httpPost(`buss/modifyFeeApply/listPageAddLedger`, this.search).then(res => {
        if (res.status == 1) {
          this.list = res.data.content
          this.search.total = res.data.totalElements
          this.totalMoney = res.totalMoney
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },
    /*  操作 */
    showDialog(type, typeName, detailId) {
      console.log(this.search.sectionId);
      if (!this.search.sectionId) {
        this.$messageWarning("请选择【标段】后再添加数据")
        return;
      }




      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
            addSectionId: this.addSectionId,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            contractFiling.del(param).then(res => {
              if (res.code === 200) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break

      }
    },




  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.list_wrap {
  margin-top: 20px;
}
.left-box {
  min-width: 220px !important;
  max-width: 350px !important;
  max-height: calc(100vh - 200px);
  border-right: 1px #e2e8ec solid;
  overflow: auto;
  p {
    cursor: pointer;
    font-size: 14px;
  }
}
.right-box {
  width: calc(100% - 200px);
  padding-left: 15px;
  flex-grow: 1;
}
</style>
